# -*- coding: utf-8 -*-
# @Author : Yuan
from rest_framework import serializers, status
from rest_framework.response import Response

from apps.goods.models import Brand


class BrandModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Brand
        fields = '__all__'

    def create(self, validated_data):
        logo_data = validated_data.get('logo')
        from fdfs_client.client import Fdfs_client
        f_client = Fdfs_client('utils/fastdfs/client.conf')
        res = f_client.upload_by_buffer(logo_data.read())
        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)
        logo_url = res['Remote file_id']
        validated_data['logo'] = logo_url
        return super().create(validated_data)

    def update(self, instance, validated_data):
        logo_data = validated_data.get('logo')
        name = validated_data.get('name')
        first_letter = validated_data.get('first_letter')
        from fdfs_client.client import Fdfs_client
        f_client = Fdfs_client('utils/fastdfs/client.conf')
        res = f_client.upload_by_buffer(logo_data.read())
        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)
        logo_url = res['Remote file_id']
        instance.name = name
        instance.first_letter = first_letter
        instance.logo = logo_url
        instance.save()
        return instance
        # validated_data['logo'] = logo_url
        # return super().update(instance, validated_data)


